<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>baidu TTS语音合成测试</title><!-- 这里调用的是百度文字转语音开放API -->
</head>

<body>
<div>
  <input type="text" id="ttsText">
  <input type="button" id="tts_btn" onclick="doTTS()" value="播放">
  <p><span>语音识别：</span>
    <input type="text" id="readText"/>
    <input type="button" id="read_btn" onclick="doSpeech()" value="开始说话">
    <input type="button" id="stop_btn" onclick="stopSpeech()" value="停止">
  </p>
  <p><input type="text" x-webkit-speech /> </p>
</div>
<div id="bdtts_div_id">
  <audio id="tts_autio_id" autoplay="autoplay">
    <source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&amp;ie=UTF-8&amp;spd=5&amp;per=1&amp;text=请输入文字" type="audio/mpeg">
    <embed id="tts_embed_id" height="0" width="0" src="">
  </audio>
</div>
</body>

<script src="../jquery-1.8.3.min.js"></script>
<script>
function doTTS() {
var ttsDiv = document.getElementById('bdtts_div_id');
var ttsAudio = document.getElementById('tts_autio_id');
var ttsText = document.getElementById('ttsText').value;

// 文字转语音
ttsDiv.removeChild(ttsAudio);
var au1 = '<audio id="tts_autio_id" autoplay="autoplay">';
var sss = '<source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&per=3&spd=5&text=' + ttsText + '" type="audio/mpeg">';
var eee = '<embed id="tts_embed_id" height="0" width="0" src="">';
var au2 = '</audio>';
ttsDiv.innerHTML = au1 + sss + eee + au2;

ttsAudio = document.getElementById('tts_autio_id');

ttsAudio.play();
}

/*
代码中改变传参可更改配置：

lan=zh（语言zh:中文；en:英文；fr:法文；）

ie=UTF-8（字符集）

per=3（每3个字符停顿）

spd=5（语音播放速度，数字越大越快0-15）

text=“”（需要转换的文字）*/

var msg = new SpeechSynthesisUtterance("hello 欢迎测试TTS");
console.log(msg);
window.speechSynthesis.speak(msg);

var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onresult = function(event) {
 console.log(event)
}


function doSpeech() {
  recognition.start();
}
function stopSpeech() {
  recognition.stop();
}
</script>

</html>